﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using Chire.ChireInter.Class;
using Chire.ChireInter.Motto;
using Chire.ChireInter.Order;
using Chire.ChireInter.Parent;
using Chire.ChireInter.Students;
using Chire.ChireInter.Teacher;
using Chire.ChireInter.Wechat;
using Chire.wechat;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Chire.ChireInter.Sign
{
    /// <summary>
    /// Sign_Login 的摘要说明
    /// </summary>
    public class Sign_Login : IHttpHandler
    {
        HttpContext contextWithBase;
        string code = "";                   // 身份id
        string openid = "";
        string signType = "";              // 1签到 3签退

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            contextWithBase = context;
            analysisInfo();
        }

        #region 验证信息
        public void analysisInfo()
        {
            if (contextWithBase.Request.Form.AllKeys.Contains("code"))
            {
                code = contextWithBase.Request.Form["code"];
            }
            if (contextWithBase.Request.Form.AllKeys.Contains("openid"))
            {
                openid = contextWithBase.Request.Form["openid"];
            }
            if (contextWithBase.Request.Form.AllKeys.Contains("signType"))
            {
                signType = contextWithBase.Request.Form["signType"];
            }
            mainManager();
        }
        #endregion

        #region 签到签退主方法
        public void mainManager(){
            // 1. 获取微信信息
            Wechat_Action wechatAction = new Wechat_Action();
            if (openid.Length <= 0)
            {
                openid = wechatAction.getOpenIdWithCode(code);
            }

            // 2. 判断是签到还是签退
            if (signType.Equals("1") == true)
            {         // 签到
                signInManager();
            }
            else if (signType.Equals("3") == true)
            {                  // 签退
                signOutManager();
            }
        }
        #endregion

        #region 签到方法
        public void signInManager() { 
            // 1. 获取学生
            Student_Action studentAction = new Student_Action();
            Sign_Action signAction = new Sign_Action();
            Student_Model studentModel = studentAction.getStudentIdWithOpenId(openid);
            // 1.1 获取课程信息
            Class_Action classAction = new Class_Action();
            Class_Model classModel = classAction.getClassInfoWithId(studentModel.classid);
            // 

            // 2. 判断是否有学生
            if (studentModel.id != null)
            {      // 有学生
                // 3.判断今天是否签到过了
                bool hasSignIn = signAction.signHasSignIn(studentModel.id, studentModel.classid);
                if (hasSignIn == true)
                {        // 已经签到了
                    successManager("501", "已签到", null);
                }
                else
                {   // 没有签到
                    // 1. 判断地址是否合格
                    List<double> distanceList = signAction.adjustAddressDistance(openid);
                    double minDistance = distanceList.Min();

                    if (minDistance < 0.5 || true)
                    {
                        // 3.1 进行签到方法
                        signAction.signSignInManager(studentModel.id, studentModel.classid);
                        // 3.2 进行接口返回
                        successModelManager(studentModel.id, classModel);
                        // 3.4 微信进行发送消息
                        wechatSendSignInMsg(openid, studentModel, classModel, classModel.teacher);
                      
                    }
                    else {
                        successManager("502", "请确认距离教室500米内(现距离" + Convert.ToInt32(minDistance * 1000) + "米)，或者查看微信是否提供位置信息", null);
                    }
                }
            }
            else {
                successManager("401", "没有账户权限", null);
            }  
        }
        #endregion

        #region 签退方法
        public void signOutManager(){
            // 1. 获取学生
            Student_Action studentAction = new Student_Action();
            Sign_Action signAction = new Sign_Action();
            Student_Model studentModel = studentAction.getStudentIdWithOpenId(openid);
            // 1.1 获取课程信息
            Class_Action classAction = new Class_Action();
            Class_Model classModel = classAction.getClassInfoWithId(studentModel.classid);
            if (studentModel.id != null)
            {  // 有学生
                // 2.1 判断今天是否签退过了
                bool hasSignOut = signAction.signHasSignOut(studentModel.id, studentModel.classid);
                if (hasSignOut == true)
                {
                    successManager("502", "已签退", null);
                }
                else { 
                    // 1. 进行签退方法
                    signAction.signSignOutManager(studentModel.id, studentModel.classid);
                    // 2. 进行接口返回
                    successModelManager(studentModel.id,classModel);
                    // 3. 进行微信返回
                    wechatSendSignOutMsg(openid,studentModel,classModel,classModel.teacher);
                    // 3.3 进行计算课时
                    //Order_Action orderAction = new Order_Action();
                    //orderAction.signOutCalculationClassTime(studentModel.classid, studentModel.id);
                }
            }
            else {
                successManager("401", "没有账户权限", null);
            }
        }
        #endregion

        #region 成功方法
        public void successModelManager(string student_id, Class_Model classModel ) {
            Sign_Model signModel = new Sign_Model();
            signModel.classModel = classModel;
            signModel.student_id = student_id;
            signModel.date = DateTime.Now.ToShortDateString().ToString();
            signModel.time = DateTime.Now.ToString();
            successManager("200", "success", signModel);
        }


        public void successManager(string errcode,string error,Sign_Model signModel)
        {
            OUTSign_Model out_base_setting = new OUTSign_Model();
            out_base_setting.errCode = errcode;
            out_base_setting.errMsg = error;
            out_base_setting.data = signModel;

            JsonSerializer serializer = new JsonSerializer();
            StringWriter sw = new StringWriter();
            serializer.Serialize(new JsonTextWriter(sw), out_base_setting);
            string info = sw.GetStringBuilder().ToString();
            contextWithBase.Response.Write(sw.GetStringBuilder().ToString());
        }
        #endregion

        #region 进行微信签到发送信息
        public void wechatSendSignInMsg(string openid,Student_Model student,Class_Model classInfo,Teacher_Model teacher) {
            Wechat_AccessToken wechatToken = new Wechat_AccessToken();

            WechatModelData first = new WechatModelData();
            first.value = "【炽热教育】签到";
            first.color = "#FF0000";

            WechatModelData keyword1 = new WechatModelData();
            keyword1.value = student.name;
            keyword1.color = "#173177";

            WechatModelData keyword2 = new WechatModelData();
            keyword2.value = classInfo.name + "课程";
            keyword2.color = "#173177";

            WechatModelData keyword3 = new WechatModelData();
            keyword3.value = DateTime.Now.ToString();
            keyword3.color = "#173177";

            WechatModelData keyword4 = new WechatModelData();
            keyword4.value = "签到成功";
            keyword4.color = "#173177";

            WechatModelData keyword5 = new WechatModelData();
            keyword5.value = teacher.name;
            keyword5.color = "#173177";

            WechatModelData remark = new WechatModelData();
            remark.value = getMotto();
            remark.color = "#173177";

            WechatModelDataList list = new WechatModelDataList();
            list.first = first;
            list.keyword1 = keyword1;
            list.keyword2 = keyword2;
            list.keyword3 = keyword3;
            list.keyword4 = keyword4;
            list.keyword5 = keyword5;
            list.remark = remark;

            wechatToken.sendMsgWithSignIn(openid, list);
            // 进行家长签到通知
            wechatSendSignInWithParentMsg(openid, student, classInfo, teacher);
        }

        public void wechatSendSignInWithParentMsg(string openid, Student_Model student, Class_Model classInfo, Teacher_Model teacher)
        {
            Wechat_AccessToken wechatToken = new Wechat_AccessToken();

            WechatModelData first = new WechatModelData();
            first.value = "【炽热教育】签到";
            first.color = "#FF0000";

            WechatModelData keyword1 = new WechatModelData();
            keyword1.value = student.name;
            keyword1.color = "#173177";

            WechatModelData keyword2 = new WechatModelData();
            keyword2.value = classInfo.name + "课程";
            keyword2.color = "#173177";

            WechatModelData keyword3 = new WechatModelData();
            keyword3.value = DateTime.Now.ToShortTimeString();
            keyword3.color = "#173177";

            WechatModelData keyword4 = new WechatModelData();
            keyword4.value = "签到成功";
            keyword4.color = "#173177";

            WechatModelData keyword5 = new WechatModelData();
            keyword5.value = teacher.name;
            keyword5.color = "#173177";

            WechatModelData remark = new WechatModelData();
            remark.value = "尊敬的" + student.name + "家长,您好。" + student.name + "已签到并进行" + classInfo.name + "的学习。学生的成功养离不开您的培养，谢谢。";
            remark.color = "#173177";

            WechatModelDataList list = new WechatModelDataList();
            list.first = first;
            list.keyword1 = keyword1;
            list.keyword2 = keyword2;
            list.keyword3 = keyword3;
            list.keyword4 = keyword4;
            list.keyword5 = keyword5;
            list.remark = remark;

            // 1. 获取家长信息
            Parent_Action parentAction = new Parent_Action();
            List<Parent_Model> parentList = parentAction.getAllParentWithStudentId(student.id);
            for (int i = 0; i < parentList.Count; i++) {
                Parent_Model parentModel = parentList[i];
                wechatToken.sendMsgWithSignIn(parentModel.openid, list);
            }
        }

        #endregion

        #region 进行微信签退发送信息
        public void wechatSendSignOutMsg(string openid, Student_Model student, Class_Model classInfo, Teacher_Model teacher)
        {
            Wechat_AccessToken wechatToken = new Wechat_AccessToken();

            WechatModelData first = new WechatModelData();
            first.value = "【炽热教育】签退";
            first.color = "#FF0000";

            WechatModelData keyword1 = new WechatModelData();
            keyword1.value = student.name;
            keyword1.color = "#173177";

            WechatModelData keyword2 = new WechatModelData();
            keyword2.value = DateTime.Now.ToShortTimeString();
            keyword2.color = "#173177";

            WechatModelData keyword3 = new WechatModelData();
            keyword3.value = classInfo.name + "课程";
            keyword3.color = "#173177";

            WechatModelData remark = new WechatModelData();
            remark.value = getMotto();
            remark.color = "#173177";

            WechatModelDataList list = new WechatModelDataList();
            list.first = first;
            list.keyword1 = keyword1;
            list.keyword2 = keyword2;
            list.keyword3 = keyword3;

            list.remark = remark;

            wechatToken.sendMsgWithSignOut(openid, list);
            // 进行家长签到通知
            wechatSendSignOutMsgWithParent(openid, student, classInfo, teacher);
        }

        public void wechatSendSignOutMsgWithParent(string openid, Student_Model student, Class_Model classInfo, Teacher_Model teacher)
        {
            Wechat_AccessToken wechatToken = new Wechat_AccessToken();

            WechatModelData first = new WechatModelData();
            first.value = "【炽热教育】签退";
            first.color = "#FF0000";

            WechatModelData keyword1 = new WechatModelData();
            keyword1.value = student.name;
            keyword1.color = "#173177";

            WechatModelData keyword2 = new WechatModelData();
            keyword2.value = DateTime.Now.ToString();
            keyword2.color = "#173177";

            WechatModelData keyword3 = new WechatModelData();
            keyword3.value = classInfo.name + "课程";
            keyword3.color = "#173177";

            WechatModelData remark = new WechatModelData();
            remark.value = "尊敬的" + student.name + "家长,您好" + student.name + "已结束" + classInfo.name + "的学习。";
            remark.color = "#173177";

            WechatModelDataList list = new WechatModelDataList();
            list.first = first;
            list.keyword1 = keyword1;
            list.keyword2 = keyword2;
            list.keyword3 = keyword3;
            list.remark = remark;


            // 1. 获取家长信息
            Parent_Action parentAction = new Parent_Action();
            List<Parent_Model> parentList = parentAction.getAllParentWithStudentId(student.id);
            for (int i = 0; i < parentList.Count; i++)
            {
                Parent_Model parentModel = parentList[i];
                wechatToken.sendMsgWithSignOut(parentModel.openid, list);
            }
        }


        #endregion

        #region 获取箴言
        public string getMotto() {
            Motto_Action mottoAction = new Motto_Action();
            return mottoAction.getMotto();
        }
        #endregion

        #region 其他
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        #endregion
     
    }
}